package com.zhangjingcheng.yunyixia.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zhangjingcheng.yunyixia.interceptior.JwtTokenInterceptor;
import com.zhangjingcheng.yunyixia.json.JacksonTimeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private JwtTokenInterceptor jwtTokenInterceptor;

    /**
     * 添加拦截器
     *
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtTokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/user/register", "/user/resetPwd", "/user/qqLogin"
                ,"/checkCode", "/sendEmailCode","/user/getUserInfo","/images/**", "/preview/**");
    }

    /**
     * 扩展消息转换器
     *
     * @param converters
     */
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new JacksonTimeMapper());
        converters.add(0, converter);
    }

    /**
     * 映射静态资源
     *
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取项目根路径
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String projectRoot = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
        // 拼接上传目录
        String uploadDir = Paths.get(projectRoot, "src", "main", "resources", "image").toString();

        // 映射/images/**到上传目录
        registry.addResourceHandler("/image/**")
                .addResourceLocations("file:" + uploadDir + File.separator);
    }

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }

}
